const cluster = require('node:cluster');

const isMainCluster =
  process.env.NODE_APP_INSTANCE === undefined ||
  Number.parseInt(process.env.NODE_APP_INSTANCE, 10) === 0;

const isMainProcess = cluster.isPrimary || isMainCluster;

const isDevEnvironment = process.env.NODE_ENV === 'development';

const getEnvBoolean = (key, defaultValue) => {
  const value = process.env[key];
  return value !== undefined ? value === 'true' : defaultValue;
};

const getEnvString = (key, defaultValue) => {
  const value = process.env[key];
  return value ?? defaultValue;
};

const getEnvNumber = (key, defaultValue) => {
  const value = process.env[key];
  if (value) {
    const parsed = parseInt(value, 10);
    return !isNaN(parsed) ? parsed : defaultValue;
  }
  return defaultValue;
};

module.exports = {
  isMainCluster,
  isMainProcess,
  isDevEnvironment,
  getEnvBoolean,
  getEnvString,
  getEnvNumber,
};
